/* $RCSFile: IpnHandler.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/IPNReceipt/IpnHandler.aspx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:11  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Text;
using System.Globalization;

using AddonNice;
using AddonNice.Configuration;
using AddonNice.Authentication;
using AddonNice.Security;
using AddonNice.Diagnostics;

using AddonNice.ECommerce;
using AddonNice.Settings.ECommerce;
using AddonNice.ECommerce.UI;
using AddonNice.ECommerce.Gateways.Payment;
using AddonNice.ECommerce.UI.WebControls;

using Trace2    =   System.Diagnostics.Trace;


namespace AddonNice.IPNReceipt
{
	/// <summary>
	/// Handles the IPN post back message from PayPal
	/// </summary>
	public partial class IpnHandler : IPNPage
	{
	
        void IpnHandler_Load(object sender, EventArgs e)
		{
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler Page_Load date: {0}",DateTime.UtcNow),IPNTraceSwitch.Sw.Info);
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler {0} values in Request.Form:",Request.Form.Count),IPNTraceSwitch.Sw.Info);
			string	RawTransac			=	Request.Form.ToString();
			string strNewValue			=	RawTransac + "&cmd=_notify-validate";
			
			// Create the request back
			HttpWebRequest req			=	(HttpWebRequest) WebRequest.Create("https://www.paypal.com/cgi-bin/webscr");

			// Set values for the request back
			req.Method					=	"POST";
			req.ContentType				=	"application/x-www-form-urlencoded";
			req.ContentLength			=	strNewValue.Length;

			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler ContentType: {0}",HttpContext.Current.Request.ContentType),IPNTraceSwitch.Sw.Info);
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler ContentEncoding: {0}",HttpContext.Current.Request.ContentEncoding),IPNTraceSwitch.Sw.Info);
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler aknowledge sent to Paypal server strnewValue: {0}",strNewValue),IPNTraceSwitch.Sw.Info);

			// Write the request back IPN strings
			StreamWriter stOut			=	null;
			try
			{
				stOut					=	new StreamWriter (req.GetRequestStream(), System.Text.Encoding.ASCII);
				stOut.Write(strNewValue);
			}
			catch(Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load stOut.Write ex: {0}",ex),IPNTraceSwitch.Sw.Info);
			}
			finally
			{
				try
				{
					stOut.Close();
				}
				catch(Exception ex)
				{
					if (IPNTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load stOut.Close ex: {0}",ex),IPNTraceSwitch.Sw.Info);
				}
			}

			// Do the request to PayPal and get the response
			StreamReader stIn			=	new StreamReader(req.GetResponse().GetResponseStream());
			string strResponse			=	string.Empty;
			try
			{
				strResponse				=	stIn.ReadToEnd();
			}
			catch(Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load stIn.ReadToEnd ex: {0}",ex),IPNTraceSwitch.Sw.Info);
			}
			finally
			{
				try
				{
					stIn.Close();
				}
				catch(Exception ex)
				{
					if (IPNTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load stIn.Close ex: {0}",ex),IPNTraceSwitch.Sw.Info);
				}
			}
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler response read from Paypal server date: {0}, strResponse: {1}",
                    DateTime.UtcNow,strResponse),IPNTraceSwitch.Sw.Info);
			// Not acknowledged from Paypal
			bool VerifiedByPaypal	=	( strResponse == "VERIFIED" );
			if ( !VerifiedByPaypal ) 
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler PayPal NO AKNOWLEDGE date: {0}, response: {1},  payment_status: {2}",DateTime.UtcNow,strResponse, Request.Form["payment_status"]),IPNTraceSwitch.Sw.Info);
				if ( Request.Form["payment_status"] == null )
				{
					if (IPNTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler Payment Status = null at {0}",DateTime.UtcNow,strResponse),IPNTraceSwitch.Sw.Info);
					InsertRawTransac(RawTransac);
					return;
				}
			}

			object	obj					=	Request.Form["custom"];
			if ( obj == null || (string)obj == string.Empty )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler Err custom==null date : {0}\nRawTransac : {1}",DateTime.UtcNow,RawTransac),IPNTraceSwitch.Sw.Info);
				FindTransacFromUser(RawTransac,VerifiedByPaypal);
				return;
			}
			string	custom				=	(string)obj;
			string[] CodeStr			=	PaymentGtwBase.DecodeMark(custom);
			int TransacID				=	int.Parse(CodeStr[0]);
			Guid MerchantID				=	new Guid(CodeStr[1]);
			Guid OrderID				=	new Guid(CodeStr[2]);
			Guid UserID					=	new Guid(CodeStr[3]);
			string	Key2Ckeck			=	CodeStr[4];
			DateTime TransacDate		=	DateTime.UtcNow;
			try
			{
				new PaymentsDB().InsertReceivedIPN(TransacID,OrderID,MerchantID,TransacDate,RawTransac);
			}
			catch(Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load Err Inserting Transac ex : {0}\n, RawTransac :\n{1}",ex,RawTransac.Substring(0,20)),IPNTraceSwitch.Sw.Info);
				InsertRawTransac(RawTransac);
			}
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler Page_Load GetGatewayWithData date: {0}, MerchantID : {1}",DateTime.UtcNow,MerchantID),IPNTraceSwitch.Sw.Info);
			PaymentGtwBase gateway			=	new PaymentGtwManager().GetGatewayWithData("Paypal", MerchantID);									
			// we finalize the order
			gateway.InitFromResponse(Request.Form,custom);
			Order2 o						=	new Order2();
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler Page_Load Order.Finalize(true) date: {0}",DateTime.UtcNow),IPNTraceSwitch.Sw.Info);
			try
			{
				o.Finalize(new FinalizeOrder(),gateway, true);
			}
			catch(Exception ex )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler IpnHandler_Load Err Finalize ex : {0}",ex.Message),IPNTraceSwitch.Sw.Info);
			}
		}
		
		/// <summary>
		/// The paypal account for the payment is not in DB we store it in a temporary table which will be checked when entering the 
		/// new orders from ebay or other
		/// </summary>
		void StoreUserInfo(bool VerifiedByPaypal,bool ShouldIncludeDate)
		{
			System.Globalization.CultureInfo ci				=	new System.Globalization.CultureInfo("en-US");
			ci.NumberFormat.CurrencyDecimalSeparator		=	".";
			string payer_email				=	string.Empty;
			string first_name				=	string.Empty;
			string last_name				=	string.Empty;
			string address_street			=	string.Empty;
			string address_zip				=	string.Empty;
			string address_city				=	string.Empty;
			string address_state			=	string.Empty;
			string address_country			=	string.Empty;
			decimal mc_gross				=	0m;
			decimal mc_fee					=	0m;
			string payer_id					=	string.Empty;
			DateTime payment_date			=	DateTime.UtcNow;
			string payment_type				=	string.Empty;
			DateTime auction_closing_date	=	DateTime.UtcNow;
			string auction_buyer_id			=	string.Empty;
			int quantity					=	0;
			string txn_id					=	string.Empty;
			string txn_type					=	string.Empty;
			string item_number				=	string.Empty;
			string item_name				=	string.Empty;
			string mc_currency				=	string.Empty;
			bool for_auction				=	false;
			bool address_status				=	false;
			bool payer_status				=	false;
			PaymentsDB pdb					=	new PaymentsDB();
			try
			{
				if ( Request.Form["payer_email"] != null )
					payer_email				=	Request.Form["payer_email"];
				if ( Request.Form["first_name"] != null )
					first_name				=	Request.Form["first_name"];
				if ( Request.Form["last_name"] != null )
					last_name				=	Request.Form["last_name"];
				if ( Request.Form["address_street"] != null )
					address_street			=	Request.Form["address_street"];
				if ( Request.Form["address_zip"] != null )
					address_zip				=	Request.Form["address_zip"];
				if ( Request.Form["address_city"] != null )
					address_city				=	Request.Form["address_city"];
				if ( Request.Form["address_state"] != null )
					address_state			=	Request.Form["address_state"];
				if ( Request.Form["address_country"] != null )
					address_country			=	Request.Form["address_country"];
				if ( Request.Form["mc_gross"] != null && Request.Form["mc_gross"] != string.Empty )
					mc_gross				=	Decimal.Parse(Request.Form["mc_gross"],ci);
				if ( Request.Form["mc_fee"] != null && Request.Form["mc_fee"] != string.Empty )
					mc_fee					=	Decimal.Parse(Request.Form["mc_fee"],ci);
				if ( Request.Form["payer_id"] != null )
					payer_id					=	Request.Form["payer_id"];
				if ( Request.Form["payment_date"] != null )
					payment_date			=	ConvertIpnDate(Request.Form["payment_date"]);
				if ( Request.Form["payment_type"] != null )
					payment_type				=	Request.Form["payment_type"];
				if ( Request.Form["auction_closing_date"] != null )
					auction_closing_date	=	ConvertIpnDate(Request.Form["auction_closing_date"]);
				if ( Request.Form["auction_buyer_id"] != null )
					auction_buyer_id			=	Request.Form["auction_buyer_id"];
				if ( Request.Form["quantity"] != null && Request.Form["quantity"] != string.Empty )
					quantity					=	int.Parse(Request.Form["quantity"]);
				if ( Request.Form["txn_id"] != null )
					txn_id					=	Request.Form["txn_id"];
				if ( Request.Form["txn_type"] != null )
					txn_type					=	Request.Form["txn_type"];
				if ( Request.Form["item_number"] != null )
					item_number				=	Request.Form["item_number"];
				if ( Request.Form["item_name"] != null )
					item_name				=	Request.Form["item_name"];
				if ( Request.Form["mc_currency"] != null )
					mc_currency				=	Request.Form["mc_currency"];
				if ( Request.Form["for_auction"] != null && Request.Form["for_auction"] != string.Empty )
					for_auction				=	bool.Parse(Request.Form["for_auction"]);
				if ( Request.Form["address_status"] != null && Request.Form["address_status"] == "confirmed" )
					address_status				=	true;
				if ( Request.Form["payer_status"] != null && Request.Form["payer_status"] == "verified" )
					payer_status				=	true;
			}
			catch( Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler StoreUserInfo ex: {0}",ex),IPNTraceSwitch.Sw.Info);
			}
			// Whatever happened we try to insert
			try
			{
				pdb.AddPayPalPayment(payer_email,
					first_name,
					last_name,
					address_street,
					address_zip,
					address_city,
					address_state,
					address_country,
					mc_gross,
					mc_fee,
					payer_id,
					payment_date,
					payment_type,
					auction_closing_date,
					auction_buyer_id,
					quantity,
					txn_id,
					txn_type,
					item_number,
					item_name,
					mc_currency,
					for_auction,
					address_status,
					payer_status,
					VerifiedByPaypal,
					ShouldIncludeDate);
			}
			catch( Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler StoreUserInfo AddPayPalPayment ex: {0}",ex),IPNTraceSwitch.Sw.Info);
			}
		}
		/// <summary>
		/// Try to see if the Paypal email corresponding to the payment is already in DB
		/// </summary>
		void FindTransacFromUser(string	RawTransac,bool VerifiedByPaypal)
		{
			string usermail				=	Request.Form["payer_email"];
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser usermail : {0}",usermail),IPNTraceSwitch.Sw.Info);
			// we continue to store info even with user unknown
			if ( usermail == string.Empty )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser Not Found txn_id : '{0}', txn_type : '{1}'",Request.Form["txn_id"],Request.Form["txn_type"]),IPNTraceSwitch.Sw.Info);
				usermail				=	"unknown";
			}
			decimal TotalOrder			=	0;
			string TotalOrderStr		=	string.Empty;
			try
			{
				TotalOrderStr			=	Request.Form["mc_gross"];
				System.Globalization.CultureInfo ci				=	new System.Globalization.CultureInfo("en-US");
				ci.NumberFormat.CurrencyDecimalSeparator		=	".";
				if ( TotalOrderStr != null && TotalOrderStr != string.Empty )
					TotalOrder			=	Decimal.Parse(TotalOrderStr,ci);
				if ( TotalOrder == 0 )
				{
					TotalOrderStr		=	Request.Form["amount"];
					if ( TotalOrderStr != null && TotalOrderStr != string.Empty )
						TotalOrder			=	Convert.ToDecimal(TotalOrderStr,ci);
				}
			}
			// we continue to store info even with userid set to -1
			catch( Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser TotalOrder  ex: {0}, usermail: {1}, TotalOrderStr: {2}",
                        ex,usermail,TotalOrderStr),IPNTraceSwitch.Sw.Info);
			}
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser TotalOrder: {0}",TotalOrder),IPNTraceSwitch.Sw.Info);
			// we continue to store info even with userid set to -1
			if ( TotalOrder <= 0 )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser UserMail: '{0}' TotalOrder: {1}",usermail,TotalOrder),IPNTraceSwitch.Sw.Info);
			}
            AddonNiceMembershipUser usr =   (AddonNiceMembershipUser )Membership.GetUser();
			Guid UserID					=	(Guid)usr.ProviderUserKey;
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser usermail: {0}, CustomerID: {1}",usermail,UserID),IPNTraceSwitch.Sw.Info);
			if ( UserID == Guid.Empty)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser Not Found usermail: {0}, CustomerID: {1}",usermail,UserID),IPNTraceSwitch.Sw.Info);
				InsertRawTransac(RawTransac);
				StoreUserInfo(VerifiedByPaypal,false);
				return;
			}

			
			Orders2DB	Odb				=	new Orders2DB();
			SqlDataReader dr			=	null;
			Guid	OrderID				=	Guid.Empty;
			try
			{
				dr						=	Odb.GetOrdersByUser(UserID);
				/*
				 *         o.OrderID,
        o.CustomerID, 
        o.TotalGoods, 
        o.TotalDiscount,
        o.TotalShipping, 
        o.TotalTaxes, 
        o.TotalExpenses, 
        o.Status, 
        o.DateCreated, 
        o.DateModified, 
        o.PaymentProvider, 
        o.ShippingProvider, 
        o.TotalWeight, 
        o.ShippingData, 
        o.BillingData, 
        o.TransactionID, 
        o.AuthCode, 
        adn_Users.Name, 
        adn_Users.Company
*/
				while ( dr.Read() )
				{
					OrderStatus Status	    =	(OrderStatus)((int)dr[EComStStr.DBStatus]);
					decimal TotalGoods		=	(decimal)dr[EComStStr.DBTotalGoods];
					decimal TotalShipping	=	(decimal)dr[EComStStr.DBTotalShipping];
					decimal TotalTaxes		=	(decimal)dr[EComStStr.DBTotalTaxes];
					decimal TotalDiscount	=	(decimal)dr[EComStStr.DBTotalDiscount];
					decimal TotalExpenses	=	(decimal)dr[EComStStr.DBTotalExpenses];
					decimal Total2			=	TotalGoods+TotalShipping+TotalTaxes+TotalExpenses-TotalDiscount;
					if (IPNTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser Found OrderID: {0}",
                            (Guid)dr[EComStStr.DBOrderID]),IPNTraceSwitch.Sw.Info);
					if (IPNTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser TotalPayPal: {0}, TotalInDB: {1}",TotalOrder,Total2),IPNTraceSwitch.Sw.Info);
					if ( Status == OrderStatus.ToBeCompleted && TotalOrder == Total2 )
					{
						OrderID	=	(Guid)dr[EComStStr.DBOrderID];
						break;
					}

				}
			}
			catch(Exception ex )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser ex: {0}",ex),IPNTraceSwitch.Sw.Info);
				// we keep received paypal info 
				StoreUserInfo(VerifiedByPaypal,false);
				// we store raw data
				InsertRawTransac(RawTransac);
				return;
			}
			finally
			{
				if ( dr != null )
					dr.Close();
			}
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser OrderID: {0}",OrderID),IPNTraceSwitch.Sw.Info);
			// We can'tfind a corresponding order, we simply store the payment in paypal received payments, this will be completed by entering an orderexternal 
			// and selecting this payment
			if ( OrderID == Guid.Empty )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser Not Found OrderID: {0}",OrderID),IPNTraceSwitch.Sw.Info);
				//store paypal info before leaving
				StoreUserInfo(VerifiedByPaypal,false);
                InsertRawTransac(RawTransac);
				return;
			}
			OrderExternal o				=	new  OrderExternal();
			o.Load(OrderID);
			o.TransactionID				=	Request.Form["txn_id"];
			int TransacID				=	o.TransacID;
			Guid MerchantID				=	Guid.Empty; // unknown
			DateTime TransacDate		=	DateTime.UtcNow;
			try
			{
				new PaymentsDB().InsertReceivedIPN(TransacID,OrderID,MerchantID,TransacDate,RawTransac);
			}
			catch(Exception ex)
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser Inserting Transac ex : {0}\n, RawTransac :\n{1}",ex,RawTransac),IPNTraceSwitch.Sw.Info);
				InsertRawTransac(RawTransac);
			}
			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]IpnHandler FindTransacFromUser Updating order date: {0}, OrderID: {1}",DateTime.UtcNow,OrderID),IPNTraceSwitch.Sw.Info);
			// we keep the transac
			StoreUserInfo(VerifiedByPaypal,true);
			try
			{
				o.Status				=	OrderStatus.PaymentCompleted;
				o.Update(null);
			}
			catch(Exception ex )
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler FindTransacFromUser ex: {0}",ex),IPNTraceSwitch.Sw.Info);
			}
		}

		

		/// <summary>
		/// Converts a date and time format returned by the IPN message into a 
		/// <see cref="DateTime"/> value.
		/// <remarks>
		/// Abides by the IPN date time format as specified in the IPN specifications
		/// dated 9/19/2003. Must always be in the following sample format:<br/>
		/// <code>18:30:30 Jan 01, 2000 PDT</code>
		/// </remarks>
		/// </summary>
		/// <param name="strIpnDate">The original IPN date and time.</param>
		/// <returns>A <see cref="DateTime"/> of the IPN date and time.</returns>
		private DateTime ConvertIpnDate(string strIpnDate) 
		{
			// Get rid of the TimeZone at the end of the IPN Date Time
			string date											=	strIpnDate.Substring(0, strIpnDate.Length-3).Trim();
			try 
			{
				// Hard coded beginning/length values
				int nHour										= Int32.Parse(date.Substring(0, 2));
				int nMinute										= Int32.Parse(date.Substring(3, 2));
				int nSecond										= Int32.Parse(date.Substring(6, 2));
				// CS 31/8/04	
				System.Globalization.CultureInfo ci				=	new System.Globalization.CultureInfo("en-US");
				int nMonth										= DateTime.ParseExact(date.Substring(9, 3), "MMM",ci).Month;
				int nDay										= Int32.Parse(date.Substring(13, 2));
				int nYear										= Int32.Parse(date.Substring(17, 4));
			
				return new DateTime(nYear, nMonth, nDay, nHour, nMinute, nSecond);
			} 
			catch (FormatException ex) 
			{
				if (IPNTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]IpnHandler ConvertIpnDate ex: {0}",ex),IPNTraceSwitch.Sw.Info);
				return DateTime.UtcNow;
			}
		}


		#region Std overrides

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
            Load += new EventHandler(IpnHandler_Load);
		}

		#endregion
	}
}
